package com.heima.search.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojo.ApAssociateWords;
import com.heima.search.service.ArticleKeywordsSearchService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类的模板注释
 *
 * @author Mr.杨
 * @week 星期五
 * @date 2024-08-30    20:58:22
 */
@Service
public class ArticleKeywordsSearchServiceImpl implements ArticleKeywordsSearchService {
    public static final String URL = "https://www.baidu.com/sugrec?prod=pc&wd={}";

    @Override
    public ResponseResult<List<ApAssociateWords>> keywordsSearch(@NotNull UserSearchDto userSearchDto) {
        if (StrUtil.isEmpty(userSearchDto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = StrUtil.format(URL, userSearchDto.getSearchWords());
        //发送GET请求并获取响应
        String response = HttpUtil.get(url);
        // 解析JSON字符串
        JSONObject jsonObject = JSONUtil.parseObj(response);

        // 获取g数组
        JSONArray gArray = jsonObject.getJSONArray("g");

        List<ApAssociateWords> qValues = gArray.stream()
                .map(item -> {
                    JSONObject jsonItem = (JSONObject) item;
                    ApAssociateWords associateWords = new ApAssociateWords();
                    associateWords.setAssociateWords(jsonItem.getStr("q"));
                    return associateWords;
                })
                .collect(Collectors.toList());
        return ResponseResult.okResult(qValues);
    }
}
